﻿using System;
using System.Web;
using BikeBouncer.BusinessLayer;
using GeoIpCity;

namespace BikeBouncer.Site
{
	public class LocationManager
	{
		#region Properties

		private static LookupService CityLookup { get; set; }

		public static String RequestIP
		{
			get
			{
				String ip = HttpContext.Current.Request.Headers["CF-Connecting-IP"];

				if (String.IsNullOrWhiteSpace(ip))
				{
					return HttpContext.Current.Request.UserHostAddress;
				}

				return ip;
			}
		}

		#endregion

		#region Load

		public static void Load()
		{
			try
			{
				CityLookup = new LookupService(Settings.DataPath + "\\GeoCity.dat", LookupService.GEOIP_STANDARD);
			}
			catch
			{
				
			}
		}

		#endregion

		#region Location methods

		public static String GetIPCity()
		{
			if (CityLookup == null)
			{
				return Settings.DefaultCity;
			}

			Location l = CityLookup.getLocation(RequestIP);

			if (l != null)
			{
				return l.city;
			}

			return Settings.DefaultCity;
		}

		public static String GetIPCountry()
		{
			if (CityLookup == null)
			{
				return Settings.DefaultCountry;
			}

			Country c = CityLookup.getCountry(RequestIP);
			String code = Settings.DefaultCountry;

			if (c != null)
			{
				code = c.getCode().ToUpper();
			}

			if (String.IsNullOrEmpty(code) || code == "--")
			{
				code = Settings.DefaultCountry;
			}

			return code;
		}

		#endregion
	}
}